<template>
  <div class="admin-users">
    <h2>用户管理</h2>
    <div class="toolbar">
      <el-input v-model="searchKeyword" placeholder="用户名/手机号/邮箱" style="width:200px" @keyup.enter="fetchUsers" clearable />
      <el-select v-model="filterRole" placeholder="角色" @change="fetchUsers" style="width:120px">
        <el-option label="全部" value="" />
        <el-option label="管理员" value="ADMIN" />
        <el-option label="卖家" value="SELLER" />
        <el-option label="买家" value="BUYER" />
      </el-select>
      <el-select v-model="filterStatus" placeholder="状态" @change="fetchUsers" style="width:120px">
        <el-option label="全部" value="" />
        <el-option label="启用" value="1" />
        <el-option label="禁用" value="0" />
      </el-select>
      <el-button type="primary" @click="fetchUsers">查询</el-button>
      <el-button @click="openEditDialog(null)">新增用户</el-button>
    </div>
    <el-table :data="users" stripe style="width: 100%" v-loading="loading">
      <el-table-column prop="userId" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" />
      <el-table-column prop="nickname" label="昵称" />
      <el-table-column prop="role" label="角色">
        <template #default="scope">
          <el-tag :type="roleTagType(scope.row.role)">{{ roleLabel(scope.row.role) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="email" label="邮箱" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <el-dropdown>
            <el-button size="small" type="primary">操作</el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="openEditDialog(scope.row)">编辑</el-dropdown-item>
                <el-dropdown-item @click="resetPassword(scope.row.userId)">重置密码</el-dropdown-item>
                <el-dropdown-item divided @click="confirmDelete(scope.row.userId)" style="color:#f56c6c">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="total > pageSize"
      :current-page="page"
      :page-size="pageSize"
      :total="total"
      layout="prev, pager, next"
      @current-change="handlePageChange"
      style="margin-top: 16px; text-align: right;"
    />
    <!-- 编辑/新增弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="editForm.userId ? '编辑用户' : '新增用户'">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="用户名" prop="username" :rules="[{ required: true, message: '请输入用户名' }]">
          <el-input v-model="editForm.username" :disabled="!!editForm.userId" />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="editForm.role">
            <el-option label="管理员" value="ADMIN" />
            <el-option label="卖家" value="SELLER" />
            <el-option label="买家" value="BUYER" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="editForm.status">
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">保存</el-button>
      </template>
    </el-dialog>
    <!-- 删除确认弹窗 -->
    <el-dialog v-model="deleteDialogVisible" title="确认删除" width="300px">
      <div>确定要删除该用户吗？</div>
      <template #footer>
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="doDeleteUser">删除</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

const users = ref([]);
const loading = ref(false);
const filterRole = ref('');
const filterStatus = ref('');
const searchKeyword = ref('');
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const editDialogVisible = ref(false);
const editForm = ref({});
const deleteDialogVisible = ref(false);
const deleteUserId = ref(null);

const fetchUsers = async () => {
  loading.value = true;
  try {
    const res = await request.get('/api/admin/users', {
      params: {
        role: filterRole.value,
        status: filterStatus.value,
        keyword: searchKeyword.value,
        page: page.value,
        pageSize: pageSize.value
      }
    });
    users.value = res.list || res;
    total.value = res.total || res.length || 0;
  } catch (e) {
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (val) => {
  page.value = val;
  fetchUsers();
};

const roleLabel = (role) => {
  if (role === 'ADMIN') return '管理员';
  if (role === 'SELLER') return '卖家';
  if (role === 'BUYER') return '买家';
  return role;
};
const roleTagType = (role) => {
  if (role === 'ADMIN') return 'info';
  if (role === 'SELLER') return 'success';
  if (role === 'BUYER') return 'warning';
  return 'info';
};

const openEditDialog = (row) => {
  if (row) {
    editForm.value = { ...row };
  } else {
    editForm.value = { status: 1, role: 'BUYER' };
  }
  editDialogVisible.value = true;
};
const submitEdit = async () => {
  if (editForm.value.userId) {
    await request.put(`/api/admin/users/${editForm.value.userId}`, editForm.value);
    ElMessage.success('保存成功');
  } else {
    await request.post('/api/admin/users', editForm.value);
    ElMessage.success('新增成功');
  }
  editDialogVisible.value = false;
  fetchUsers();
};
const resetPassword = async (id) => {
  await request.post(`/api/admin/users/${id}/reset-password`);
  ElMessage.success('密码已重置为123456');
  fetchUsers();
};
const confirmDelete = (id) => {
  deleteUserId.value = id;
  deleteDialogVisible.value = true;
};
const doDeleteUser = async () => {
  await request.delete(`/api/admin/users/${deleteUserId.value}`);
  ElMessage.success('删除成功');
  deleteDialogVisible.value = false;
  fetchUsers();
};

fetchUsers();
</script>

<style scoped>
.admin-users {
  padding: 32px;
}
.toolbar {
  margin-bottom: 16px;
  display: flex;
  gap: 12px;
  align-items: center;
}
</style> 